package org.goyo.main.web.controller.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.goyo.common.baseBean.AjaxResult;
import org.goyo.common.baseBean.Constants;
import org.goyo.common.utils.JSONUtil;
import org.goyo.common.utils.Pager;
import org.goyo.common.utils.ToolUtils;
import org.goyo.main.domain.entity.system.SysResource;
import org.goyo.main.domain.entity.system.SysRole;
import org.goyo.main.domain.entity.system.SysRoleResource;
import org.goyo.main.services.system.ISysResourceService;
import org.goyo.main.services.system.ISysRoleResourceService;
import org.goyo.main.services.system.ISysRoleService;
import org.goyo.main.services.system.ISystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 系统角色
 * 
 * @author chenchuan
 * 2014年10月23日
 */
@Controller
@RequestMapping("/sysRole")
public class SysRoleController {
  protected Logger logger = LoggerFactory.getLogger(this.getClass());
	@Resource
	private ISysResourceService sysResourceService;
	@Resource
	private ISysRoleService sysRoleService;
	@Resource
	private ISysRoleResourceService sysRoleResourceService;
	@Resource
	private ISystemService systemService;
	/**
	 * 修改角色
	 * 
	 * @author chenchuan
	 * 2014年10月23日
	 */
	@RequestMapping("/alertSysRole")
	public String alertSysRole(HttpServletRequest request,Model model){
		List<SysResource> list = null;
		SysRole sysRole = null;
		String uuid = request.getParameter("uuid");
		try {
			//查询编辑
			list = sysResourceService.getAllSysResource();
			if(uuid != null){
				Map<String, Object> cond = new HashMap<String, Object>();
				cond.put("roleId", uuid);
				Pager<SysRoleResource> pager = sysRoleResourceService.findByCondition(cond, new Pager<SysRoleResource>());
				List<SysRoleResource> roleResources = pager.getList();
				sysRole = sysRoleService.findByUuid(uuid);
				for(SysResource role : list){
					for(SysRoleResource roleResource : roleResources){
						if(role.getUuid().equals(roleResource.getResourceId()))
							role.setIschecked(true);
					}
				}
			}
			model.addAttribute("list", JSONUtil.obj2Json(list));
			model.addAttribute("data", JSONUtil.obj2Json(sysRole));
			model.addAttribute("status", Constants.EDIT);
		} catch (Exception e) {
		  logger.error(e.getMessage(),e);
		}
		return "/system/sysRoleEdit";
	}
	
	/**
	 * 查看角色
	 * 
	 * @author chenchuan
	 * 2014年10月23日
	 */
	@RequestMapping("/viewSysRole")
	public String viewSysRole(HttpServletRequest request,Model model){
		List<SysResource> list = null;
		SysRole sysRole = null;
		String uuid = request.getParameter("uuid");
		try {
			//查询编辑
			list = sysResourceService.getAllSysResource();
			if(uuid != null){
				Map<String, Object> cond = new HashMap<String, Object>();
				cond.put("roleId", uuid);
				Pager<SysRoleResource> pager = sysRoleResourceService.findByCondition(cond, new Pager<SysRoleResource>());
				List<SysRoleResource> roleResources = pager.getList();
				sysRole = sysRoleService.findByUuid(uuid);
				for(SysResource role : list){
					for(SysRoleResource roleResource : roleResources){
						if(role.getUuid().equals(roleResource.getResourceId()))
							role.setIschecked(true);
					}
				}
			}
			model.addAttribute("list", JSONUtil.obj2Json(list));
			model.addAttribute("data", JSONUtil.obj2Json(sysRole));
			model.addAttribute("status", Constants.VIEW);
		} catch (Exception e) {
		  logger.error(e.getMessage(),e);
		}
		return "/system/sysRoleEdit";
	}
	
	/**
	 * 新增角色
	 * 
	 * @author chenchuan
	 * 2014年10月23日
	 */
	@RequestMapping("/addSysRole")
	public String addSysRole(HttpServletRequest request,Model model){
		List<SysResource> list = null;
		String sn = "";
		try {
			list = sysResourceService.getAllSysResource();
			sn = sysRoleService.getRoleSerialNumber();
		} catch (Exception e) {
		  logger.error(e.getMessage(),e);
		}
		model.addAttribute("list", JSONUtil.obj2Json(list));
		model.addAttribute("sn",sn);
		model.addAttribute("status", Constants.NEW);
		return "/system/sysRoleEdit";
	}
	
	
	/**
	 * 角色保存或更新
	 * 
	 * @author chenchuan
	 * 2014年10月23日
	 */
	@RequestMapping("/saveOrUpdateSysRole")
	@ResponseBody
	public AjaxResult saveOrUpdateSysRole(SysRole sysRole){
		AjaxResult result = null;
		try {
			String uuid = sysRoleService.saveOrUpdateInfo(sysRole);
			result = AjaxResult.resultSuccess("保存成功", uuid);
			systemService.refreshAuthority();
		} catch (Exception e) {
		  logger.error(e.getMessage(),e);
		  result = AjaxResult.resultFail("保存失败,请确认编号唯一。", null);
		}
		return result;
	}
	
	/**
	 * 角色删除
	 * 
	 * @author chenchuan
	 * 2014年10月23日
	 */
	@RequestMapping("/delSysRole")
	@ResponseBody
	public AjaxResult delSysRole(HttpServletRequest request){
		AjaxResult result = null;
		String rows = request.getParameter("rows");
        JSONArray jsonarray = JSONArray.fromObject(rows);
        List<SysRole> list = (List<SysRole>)JSONArray.toCollection(jsonarray, SysRole.class);
		try {
			sysRoleService.delByUuids(ToolUtils.getFiles(list,"uuid").toArray());
			result = AjaxResult.resultSuccess("删除成功", null);
		} catch (Exception e) {
		  result = AjaxResult.resultFail("删除失败", null);
		  logger.error(e.getMessage(),e);
		}
		return result;
	}
	
	/**
	 * 角色list
	 * 
	 * @author chenchuan
	 * 2014年10月23日
	 */
	@RequestMapping("/toSysRoleList")
	public String toSysRoleList(HttpServletRequest request,Model model){
		return "/system/sysRoleList";
	}
	
	@RequestMapping("/listData")
	@ResponseBody
	public String getListData(HttpServletRequest request,Model model){
		
		JSONObject data = null;
		//获取条件
		//Map<String, Object> cond = JSONUtil.json2Map(request.getParameter("cond"));
		//分页条件
		int page = Integer.parseInt(request.getParameter("page"));
		int pageSize = Integer.parseInt(request.getParameter("pagesize"));
		String sortname = request.getParameter("sortname");
		String sortorder = request.getParameter("sortorder");
		
		String where = request.getParameter("where"); 
		//分页器
		Pager pager = Pager.convert(page, pageSize, sortname, sortorder);
		try {
			pager = sysRoleService.findByCondition(where, pager);
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("Rows", pager.getList());
			map.put("Total", pager.getCount());
			data = JSONObject.fromObject(map);
		}catch (Exception e) {
		  logger.error(e.getMessage(),e);
		} 
		return data.toString();
	}
	
	
}
